/*
 * 工具集主入口
 *
 * - commander 进行包装命令
 * - 命令以插件形式导入，统一放在 plugins 目录下
 * - 读取 plugins 目录，将对应的功能注册为命令
 * - 主入口只包含读取、包装命令功能，而命令相关均在各自文件中实现，从而实现解耦
 */

const program = require('commander')
const chalk = require('chalk')
const path = require('path')
const fs = require('fs-extra')
const Utils = require('./lib/utils')
const print = require('./lib/print')

/**
 * 注册插件，插件定义字段
 * - name: 对应的终端命令
 * - description: 命令描述
 * - options: [--a, b]  可选项参数, --a:参数，b-描述
 * - action: 命令的实现
 * - help: 命令帮助 
 */
function registerPlugins(plugin) {
    let pro = program
        .command(plugin.name)
        .description(plugin.description)
    if (plugin.options) {
        for (let index = 0; index < plugin.options.length; index++) {
            pro.option(plugin.options[index][0], plugin.options[index][1])
        }
    }
    pro.action(plugin.action)
        .on('--help', plugin.help)
}

program
    .version(Utils.getPackageInfo().version)

// 自动注册 plugins 目录下的内容
const PLUGINS_DIR = path.join(__dirname, './plugins')
if (fs.existsSync(PLUGINS_DIR)) {
    let filenames = fs.readdirSync(PLUGINS_DIR)
    filenames = filenames.filter((item) => {
        return item.indexOf('.') !== 0 && item !== 'package.json' && item !== 'node_modules'
    })
    for (let index = 0; index < filenames.length; index++) {
        let subPath = `${PLUGINS_DIR}/${filenames[index]}`
        let stat = fs.statSync(subPath)
        if (stat.isDirectory()) {
            let requireContent = require(subPath)
            registerPlugins(requireContent)
        }
    }
}

program
    .command('*')
    .action((commandName) => {
        print.redLog(`命令 ${commandName} 不存在！`)
    })

program
    .parse(process.argv)

if (program.args.length == 0) {
    program.outputHelp()
}
